package com.backend.modules.system.controller;

import com.backend.common.model.R;
import com.backend.common.utils.SecurityUtils;
import com.backend.modules.system.convert.DepartmentConvert;
import com.backend.modules.system.dto.DepartmentDTO;
import com.backend.modules.system.dto.DepartmentQueryDTO;
import com.backend.modules.system.service.SysDepartmentService;
import com.backend.modules.system.vo.DepartmentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "组织架构管理", description = "组织架构相关接口")
@RestController
@RequestMapping("/v1/departments")
@RequiredArgsConstructor
public class DepartmentController {

    private final SysDepartmentService departmentService;

    @Operation(summary = "创建部门")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public R<Void> create(@Validated @RequestBody DepartmentDTO dto) {
        departmentService.create(dto);
        return R.ok();
    }

    @Operation(summary = "更新部门")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public R<Void> update(@PathVariable Long id, @Validated @RequestBody DepartmentDTO dto) {
        departmentService.update(id, dto);
        return R.ok();
    }

    @Operation(summary = "删除部门")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public R<Void> delete(@PathVariable Long id) {
        departmentService.delete(id);
        return R.ok();
    }

    @Operation(summary = "获取部门详情")
    @GetMapping("/{id}")
    public R<DepartmentVO> getById(@PathVariable Long id) {
        return R.ok(DepartmentConvert.convert(departmentService.getById(id)));
    }

    @Operation(summary = "查询部门列表")
    @GetMapping
    public R<List<DepartmentVO>> list(DepartmentQueryDTO query) {
        return R.ok(DepartmentConvert.convertList(departmentService.list(query)));
    }

    @Operation(summary = "获取部门树")
    @GetMapping("/tree")
    public R<List<DepartmentVO>> tree(DepartmentQueryDTO query) {
        return R.ok(DepartmentConvert.convertList(departmentService.getTree(query)));
    }
} 